package com.chaosyeb.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaosyeb.server.mapper.EmployeeMapper;
import com.chaosyeb.server.mapper.MailLogMapper;
import com.chaosyeb.server.pojo.*;
import com.chaosyeb.server.service.IEmployeeService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Chaos
 * @since 2021-12-04
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MailLogMapper mailLogMapper;

    /**
     * 获取员工（分页）
     *
     * @param currentPage
     * @param size
     * @param employee
     * @param beginDateScope 日期范围
     * @return
     */
    @Override
    public RespPageBean getEmployByPage(Integer currentPage, Integer size, Employee employee, LocalDate[] beginDateScope) {
        //开启分页（自动配置好分页）
        Page<Employee> page = new Page<>(currentPage, size);
        //Page<Employee> page1 = new Page<>(1,5);
        IPage<Employee> employByPage = employeeMapper.getEmployByPage(page, employee, beginDateScope);
        //因为返回要用RespPageBean ，所以新建一个RespPageBean对象作为返回
        RespPageBean respPageBean = new RespPageBean(employByPage.getTotal(), employByPage.getRecords());
        return respPageBean;
    }

    /**
     * 获取工号（自动获取并添加）
     *
     * @return
     */
    @Override
    public RespBean maxWorkId() {
        //获取最大工号的map：max(workId)  使用的是mysql的函数select
        List<Map<String, Object>> map = employeeMapper.selectMaps(new QueryWrapper<Employee>().select("max(workId)"));
        //将max+1后强转为string（Object转Integer，再转String）
        String workId = String.format("%08d", Integer.parseInt(map.get(0).get("max(workId)").toString()) + 1);
        return RespBean.success(workId);
    }

    /**
     * 添加员工
     * 发送邮件信息
     * @param employee
     * @return
     */
    @Override
    public RespBean addEmp(Employee employee) {
        //处理合同期限，保留2位小数
        LocalDate beginContract = employee.getBeginContract();
        LocalDate endContract = employee.getEndContract();
        //LocalDate的工具类处理，以指定单位计算日期，格式为天
        long days = beginContract.until(endContract, ChronoUnit.DAYS);
        //使用给定的模式和符号创建一个 DecimalFormat(用于格式化十进制数)
        DecimalFormat decimalFormat = new DecimalFormat("##.00");
        //设置日期合同期限 并格式化
        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days / 365.00)));
        //添加信息
        if (employeeMapper.insert(employee) == 1) {
            //添加成功后，并发送邮件
            //获取第一条员工信息
            Employee emp = employeeMapper.getEmployee(employee.getId()).get(0);
            //数据库记录发送的消息
            String msgId = UUID.randomUUID().toString();
            MailLog mailLog = new MailLog();
            mailLog.setMsgId(msgId);
            mailLog.setEid(employee.getId());
            mailLog.setStatus(0);
            mailLog.setRouteKey(MailConstants.MAIL_ROUTING_KEY_NAME);
            mailLog.setExchange(MailConstants.MAIL_EXCHANGE_NAME);
            //默认一开始是0
            mailLog.setCount(0);
            //重试时间=当前时间+超时时间 .plusMinutes加分钟数的意思  都是时间点
            mailLog.setTryTime(LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT));
            mailLog.setCreateTime(LocalDateTime.now());
            mailLog.setUpdateTime(LocalDateTime.now());
            //保存到数据库
            mailLogMapper.insert(mailLog);

            //发送邮件(在这边发送邮件，在mail中接收邮件)  交换机 路由键 员工对象 消息id
            rabbitTemplate.convertAndSend("MailConstants.MAIL_EXCHANGE_NAME",MailConstants.MAIL_ROUTING_KEY_NAME,
                    emp, new CorrelationData(msgId));
            return RespBean.success("添加成功！");
        }
        return RespBean.error("添加失败！");
    }

    @Override
    public List<Employee> getEmployee(Integer id) {
        return employeeMapper.getEmployee(id);
    }

    /**
     * 获取所有与员工工资账套
     * @param currentPage
     * @param size
     * @return
     */
    @Override
    public RespPageBean getEmployeeWithSalary(Integer currentPage, Integer size) {
        //开启分页
        Page<Salary> page = new Page<>(currentPage, size);
        //获取数据
        IPage<Salary> employee = employeeMapper.getEmployeeWithSalary(page);
        RespPageBean respPageBean = new RespPageBean(employee.getTotal(), employee.getRecords());
        return respPageBean;
    }

}
